import 'dart:convert';

import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:http/http.dart';
import 'package:imooc_flutter_2024/util/header_utils.dart';
import 'package:imooc_flutter_2024/util/navigator_utils.dart';
import 'package:imooc_flutter_2024/util/uri_utils.dart';
import 'package:http/http.dart' as http;

class LoginDao {
  static const String boardingpass = 'boardingpass';

  static login({required String username, required String password}) async {
    Map<String, String> paramMap = {};
    paramMap['userName'] = username;
    paramMap['password'] = password;
    Uri uri = getUri('/uapi/user/login');
    Response response =
        await http.post(uri, headers: hiHeaders(), body: paramMap);
    // Uri uri = getUri('cats');
    // Response response = await http.get(uri, headers: hiHeaders());
    Utf8Decoder utf8decoder = Utf8Decoder();
    String bodyString = utf8decoder.convert(response.bodyBytes);
    if (isRespSuccess(response)) {
      final result = json.decode(bodyString);
      if (isRespDataSuccess(result)) {
        _saveBoardingPass(result['data']);
      } else {
        throw Exception(bodyString);
      }
    } else {
      throw Exception(bodyString);
    }
  }

  static void _saveBoardingPass(String result) {
    HiCache.getInstance().setString(boardingpass, result);
  }

  static String? getBoardingPass() {
    return HiCache.getInstance().get(boardingpass);
  }

  static void logout() {
    HiCache.getInstance().remove(boardingpass);
    NavigatorUtils.gotoLogin();
  }
}
